<template>
    <div>
        <!--搜索表单-->
        <div>
            <Form ref="search" :model="search" inline :label-width="60">
                <FormItem prop="user" label="名字">
                    <Input type="text" v-model="search.name" placeholder="名字">
                    </Input>
                </FormItem>
                <FormItem prop="openid" label="openid">
                    <Input type="text" v-model="search.openid" placeholder="openid">
                    </Input>
                </FormItem>
                <FormItem prop="Phone" label="手机号">
                    <Input type="number" v-model="search.phone" placeholder="手机号">
                    </Input>
                </FormItem>
                <FormItem prop="sex" label="性别">
                    <Select v-model="search.sex" style="width: 180px">
                        <i-option v-for="item in List" :key="item.value" :value="item.value">{{ item.label }}</i-option>
                    </Select>
                </FormItem>
                <FormItem prop="sex" label="账号状态">
                    <Select v-model="search.status" style="width: 180px">
                        <i-option value="1">正常</i-option>
                        <i-option value="0">禁用</i-option>
                    </Select>
                </FormItem>
                <br>
                <FormItem prop="idCard" label="身份证号">
                    <Input type="text" v-model="search.idCard" placeholder="身份证号">
                    </Input>
                </FormItem>
                <FormItem prop="user" label="地区">
                    <Input type="text" v-model="search.address" placeholder="地区">
                    </Input>
                </FormItem>
                <FormItem prop="user" label="详细地址">
                    <Input type="text" v-model="search.houseInfo" placeholder="详细地址">
                    </Input>
                </FormItem>
                <DatePicker v-model="search.dates" format="yyyy/MM/dd" type="daterange" placement="bottom-end"
                            placeholder="选择入档日期范围" style="width: 200px;margin-left: 40px;"></DatePicker>
                <FormItem prop="field" label="排序项">
                    <Select v-model="search.field" style="width: 180px">
                        <i-option value="userId">编号</i-option>
                        <i-option value="name">名称</i-option>
                        <i-option value="phone">电话</i-option>
                        <i-option value="idCard">电话</i-option>
                        <i-option value="address">地区</i-option>
                        <i-option value="houseInfo">详细地址</i-option>
                        <i-option value="createTime">入档日期</i-option>
                    </Select>
                </FormItem>
                <FormItem prop="isAsc" label="排序">
                    <Select v-model="search.isAsc" style="width: 180px">
                        <i-option :value="1">正序</i-option>
                        <i-option :value="0">倒序</i-option>
                    </Select>
                </FormItem>
            </Form>
        </div>
        <!--表头操作按钮-->
        <div class="mb20">
            <Button type="primary" icon="ios-add-circle-outline" @click="showAddModal">添加</Button>
<!--            <Button type="error" :disabled="del_disabled" icon="md-trash" @click="deleteList" class="ml20">删除</Button>-->
<!--            <Button type="warning" icon="ios-cloud-upload-outline" @click="" class="ml20">导入</Button>-->
            <Button type="success" icon="ios-cloud-download-outline" @click="exportExcel" class="ml20">导出</Button>
            <Button type="primary" icon="ios-search" @click="searchSubmit" class="ml20">搜索</Button>
            <Button icon="md-refresh" @click="handleReset" class="ml20">Reset</Button>
        </div>
        <Table border stripe :columns="columns" :data="data" :loading="loading"
               @on-select="on_select" @on-select-cancel="on_select_cancel"
               @on-select-all="on_select_all" @on-select-all-cancel="on_select_all_cancel">
            <!--使用插槽处理自定义渲染的数据-->
            <template slot-scope="{ row, index }" slot="avatarUrl">
                <span> <Avatar :src="row.avatarUrl"/></span>
            </template>
            <template slot-scope="{ row, index }" slot="sex">
                <span>{{getSex(row.sex)}}</span>
            </template>
            <template slot-scope="{ row, index }" slot="createTime">
                <Time :time="row.createTime" type="datetime"/>
            </template>
            <template slot-scope="{ row, index }" slot="status">
                <el-switch
                        :value="getStatus(row.status)"
                        @change="changeStatus(row)">
                </el-switch>
            </template>
            <template slot-scope="{ row, index }" slot="action">
                <Button type="info" icon="md-create" size="small" @click="showChangeModal(row)"
                        style="margin-top: 5px;">修改</Button>
                <Button type="error" icon="ios-lock" size="small" @click="showResetModal(row)"
                        style="margin-top: 5px;margin-bottom: 5px;">重置
                </Button>
            </template>
        </Table>

        <Page :total="pageData.totalElements" :page-size="pageSize" show-elevator @on-change="change"
              class-name="page-style"></Page>

        <!--添加弹窗-->
        <Modal :closable=false
               title="新增住户信息"
               v-model="modal_add"
               ok-text="确定"
               @on-ok="handleAddSubmit('formAdd',formAdd)"
               class-name="vertical-center-modal">
            <div>
                <Form ref="formAdd" :model="formAdd" :rules="ruleInline">
                    <FormItem prop="name" label="名字">
                        <Input type="text" v-model="formAdd.name" placeholder="name"></Input>
                    </FormItem>
                    <FormItem prop="phone" label="手机号">
                        <Input type="number" v-model="formAdd.phone" placeholder="请输入手机号码"></Input>
                    </FormItem>
                    <FormItem prop="password" label="密码">
                        <Input type="password" v-model="formAdd.password" placeholder="请输入密码"></Input>
                    </FormItem>
                    <FormItem prop="idCard" label="身份证号">
                        <Input type="text" v-model="formAdd.idCard" placeholder="请输入身份证号码"></Input>
                    </FormItem>
                    <FormItem prop="sex" label="性别">
                        <Select v-model="formAdd.sex">
                            <i-option v-for="item in List" :key="item.value" :value="item.value">{{ item.label }}</i-option>
                        </Select>
                    </FormItem>
                    <FormItem label="省市区" prop="address">
                        <Input type="text" disabled  v-model="formAdd.address" placeholder="请输入地区"></Input>
                        <Cascader  v-model="chinaArea" :data="area" @on-change="getArea" style="width: 250px"></Cascader>
                    </FormItem>
                    <FormItem label="详细地址" prop="houseInfo">
                        <Input type="text"   v-model="formAdd.houseInfo" placeholder="请输入详细地址"></Input>
                    </FormItem>
                    <Input type="text" v-model="formAdd.avatarUrl" style="display: none;"></Input>
                    <Avatar :src="formAdd.avatarUrl" size="large"/>
                    <Upload action="/api/common/upload/avatar" :show-upload-list="false"
                            class="upload-btn" :headers="$store.state.upHeaders"
                            :on-success="onUploadChangeAvatar">
                        <i-button icon="ios-cloud-upload-outline">上传头像</i-button>
                    </Upload>
                </Form>
            </div>
        </Modal>
        <!--修改弹窗-->
        <Modal :closable=false
               title="修改住户信息"
               v-model="modal_change"
               ok-text="确定"
               @on-ok="handleSubmit('formChange',formChange)"
               class-name="vertical-center-modal">
            <div>
                <Form ref="formChange" :model="formChange" :rules="ruleInline">
                    <FormItem prop="name" label="名字">
                        <Input type="text" v-model="formChange.name" placeholder="name"></Input>
                    </FormItem>
                    <FormItem prop="phone" label="手机号">
                        <Input type="number" v-model="formChange.phone" placeholder="请输入手机号码"></Input>
                    </FormItem>
                    <FormItem prop="idCard" label="身份证号">
                        <Input type="text" v-model="formChange.idCard" placeholder="请输入身份证号码"></Input>
                    </FormItem>
                    <FormItem prop="sex" label="性别">
                        <Select v-model="formChange.sex">
                            <i-option v-for="item in List" :key="item.value" :value="item.value">{{ item.label }}</i-option>
                        </Select>
                    </FormItem>
                    <FormItem label="省市区" prop="chinaArea">
                        <Input type="text" disabled  v-model="formChange.address" placeholder="请输入地区"></Input>
                        <Cascader  v-model="chinaArea" :data="area" @on-change="getArea" style="width: 250px"></Cascader>
                    </FormItem>
                    <FormItem label="详细地址" prop="chinaArea">
                        <Input type="text"   v-model="formChange.houseInfo" placeholder="请输入详细地址"></Input>
                    </FormItem>
                    <Input type="text" v-model="formChange.avatarUrl" style="display: none;"></Input>
                    <Avatar :src="formChange.avatarUrl" size="large"/>
                    <Upload action="/api/common/upload/avatar" :show-upload-list="false" class="upload-btn"
                            :headers="$store.state.upHeaders" :on-success="onUploadChangeAvatar">
                        <i-button icon="ios-cloud-upload-outline">上传头像</i-button>
                    </Upload>
                </Form>
            </div>
        </Modal>
        <!--重置密码弹窗-->
        <Modal :closable=false
               title="重置密码提示"
               v-model="modal_reset"
               ok-text="确定"
               @on-ok="resetPassword('reset')"
               class-name="vertical-center-modal">
            <div>
                <Form ref="reset" :model="reset" :rules="ruleInline">
                    确定要重置住户 <span v-text="reset.row.name"></span> 的密码？<br/>
                    <FormItem prop="password">
                        <Input type="password" v-model="reset.password" ref="inputResetPassword"
                               placeholder="请输入新密码"></Input>
                    </FormItem>
                </Form>
            </div>
        </Modal>
    </div>

</template>

<script>
    import {dateToString, downloadExcel, exportExcel, judgePhone} from "../utils/util";
    import area from "../utils/area";

    export default {

        name: 'userinfo',
        data() {
            //手机号验证
            const phoneValidate = (rule, value, callback) => {
                let error = judgePhone(value);
                if (error===''){
                    let userId = this.formChange.userId
                    if (this.formName === 'add') userId = -1   //如果是添加用户模式
                    this.request({
                        url: '/user/phone/judge',
                        method: 'get',
                        params: {phone: value, userId: userId}
                    }).then((res) =>{
                        if (res.data===false){
                            callback(new Error('该号码已经被注册'))
                        }else {
                            //检查通过
                            callback()
                        }
                    })
                }else {
                    callback(new Error(error))
                }
            }

            return {
                loading: false,  //是否显示表格加载
                modal_add: false,
                modal_change: false,
                modal_reset: false,
                del_disabled: true,
                isSearch: false,   //当前是不是搜索模式
                List: [
                    {
                        value: 2,
                        label: '未知'
                    },
                    {
                        value: 0,
                        label: '男'
                    },
                    {
                        value: 1,
                        label: '女'
                    }
                ],
                data: [],
                current: 1,
                pageSize: 5,
                pageData: [],
                editIndex: -1,
                columns: [
                    {
                        type: 'selection',  //可以选择的一项
                        width: 55,
                        align: 'center'
                    },
                    {
                        title: '用户id',
                        key: 'userId',
                        sortable: true,
                    },
                    {
                        title: 'Avatar',
                        slot: 'avatarUrl',
                        width: 75
                    },
                    {
                        title: '用户名',
                        key: 'name'
                    },
                    {
                        title: 'openid',
                        key: 'openid'
                    },
                    {
                        title: '电话',
                        key: 'phone',
                    },
                    {
                        title: '身份证号',
                        key: 'idCard',
                    },
                    {
                        title: '性别',
                        slot: 'sex',
                        width: 62
                    },
                    {
                        title: '地区',
                        key: 'address'
                    },
                    {
                        title: '住址',
                        key: 'houseInfo'
                    },
                    {
                        title: '入档日期',
                        slot: 'createTime',
                        width: 150
                    },
                    {
                        title: '账号状态',
                        slot: 'status'
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        width: 90
                    }
                ],
                formName: '',    //提交的表单名，取值formAdd、formChange 用于电话检验
                formAdd: {
                    name: null,
                    password: null,
                    phone: null,
                    avatarUrl: null,
                    sex: 2,
                    idCard: null,
                    address: null,
                    houseInfo: null,
                    status: 1
                },
                ruleInline: {
                    name: [
                        {required: true, message: '名字不能为空', trigger: 'blur'}
                    ],
                    phone: [
                        {required: true, validator: phoneValidate, trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: 'Please fill in the password.', trigger: 'blur'},
                        {
                            type: 'string',
                            min: 6,
                            max: 20,
                            message: 'The password length cannot be less than 6 bits',
                            trigger: 'blur'
                        }
                    ],
                    idCard: [
                        {required: true, message: '身份证号不能为空', trigger: 'blur'},
                        {
                            type: 'string',
                            min: 18,
                            max: 18,
                            message: '请输入18位身份证号',
                            trigger: 'blur'
                        }
                    ],
                    address: [
                        {required: true, message: '地区不能为空', trigger: 'blur'}
                    ],
                    houseInfo: [
                        {required: true, message: '详细地址不能为空', trigger: 'blur'}
                    ]
                },
                area: area,
                chinaArea: [],
                formChange: {
                    userId: null,
                    name: null,
                    phone: null,
                    avatarUrl: null,
                    sex: null,
                    idCard: null,
                    address: null,
                    houseInfo: null
                },
                selectIds: [],     //表格中的选中项的adminId
                search: {
                    name: '',
                    phone: '',
                    openid: '',
                    idCard: '',
                    sex: null,
                    address: '',
                    houseInfo: '',
                    status: null,
                    dates: [],
                    page: 1,
                    size: 10,
                    isAsc: 1,
                    field: ''
                },
                reset: {
                    password: '',
                    row: {
                        name: ''
                    }
                }
            }
        },
        created() {
            this.query();
        },
        methods: {
            query() {
                this.loading = true  //显示表格加载动画
                this.request({
                    url: '/user',
                    method: 'get',
                    params: {page: this.current, size: this.pageSize}
                }).then(res => {
                    this.data = res.data.content
                    this.pageData = res.data
                }).finally(()=>{
                    this.loading = false
                })
            },
            change(current) {
                this.current = current;
                this.refreshData();
            },
            refreshData(){
                //刷新数据
                //判断当前页面是不是搜索模式
                if (this.isSearch){
                    this.querySearch();
                }else {
                    this.query();
                }
            },
            handleSubmit(name,data) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.loading = true
                        this.request({
                            url: '/user',
                            method: 'put',
                            data: JSON.stringify(data),
                        }).then(res => {
                            this.refreshData();        //更新修改行的数据
                            this.$Message.success(res.msg);
                        }).finally(()=>{
                            this.loading = false
                        })
                    } else {
                        this.$Message.error('填写内容不符合要求!');
                    }
                })
            },
            handleAddSubmit(name,data) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.loading = true
                        this.request({
                            url: '/user',
                            method: 'post',
                            data: JSON.stringify(data),
                        }).then(res => {
                            this.refreshData();        //更新修改行的数据
                            this.$Message.success(res.msg);
                        }).finally(()=>{
                            this.loading = false
                        })
                    } else {
                        this.$Message.error('填写内容不符合要求!');
                    }
                })
            },
            getSex(sex) {
                if (sex === 0) return '男'
                if (sex === 1) return '女'
                else return '未知'
            },
            //重置按键
            handleReset() {
                this.search = {
                    name: '',
                    phone: '',
                    openid: '',
                    idCard: '',
                    sex: null,
                    address: '',
                    houseInfo: '',
                    status: null,
                    dates: [],
                    isAsc: 1,
                    field: ''
                }
                //重置页面
                this.isSearch = false
                this.current = 1
                this.query()
            },
            showAddModal(){
                if (!this.$store.state.isAdmin){
                    this.$Message.error('你没有此操作权限!');
                    return;
                }

                this.modal_add = true;
                this.formName = 'add'    //用于电话检验
                this.formAdd = {
                        name: null,
                        password: null,
                        phone: null,
                        avatarUrl: null,
                        sex: 2,
                        idCard: null,
                        address: null,
                        houseInfo: null,
                        status: 1
                }
            },
            showChangeModal(row) {
                if (!this.$store.state.isAdmin){
                    this.$Message.error('你没有此操作权限!');
                    return;
                }

                //展示弹窗
                this.modal_change = true
                this.formName = 'change'    //用于电话检验
                //要修改的信息
                this.chinaArea = []
                this.formChange.userId = row.userId
                this.formChange.avatarUrl = row.avatarUrl
                this.formChange.name = row.name
                this.formChange.phone = row.phone
                this.formChange.sex = row.sex
                this.formChange.idCard = row.idCard
                this.formChange.address = row.address
                this.formChange.houseInfo = row.houseInfo
            },
            on_select(selection, row) {
                this.selectIds.push(row.userId)
                this.del_disabled = false //去掉删除按钮的禁用状态
            },
            on_select_cancel(selection, row) {
                this.selectIds.forEach((t, index, arr) => {
                    if (row.userId === t) {
                        arr.splice(index, 1);    //删除取消的选项
                    }
                })
                if (this.selectIds.length === 0) {
                    this.del_disabled = true //删除按钮的禁用状态
                }
            },
            on_select_all(selection) {
                selection.forEach((t, index, arr) => {
                    this.selectIds.push(t.userId)
                })
                this.del_disabled = false //去掉删除按钮的禁用状态
            },
            on_select_all_cancel(selection) {
                this.selectIds = []
                this.del_disabled = true //删除按钮的禁用状态
            },
            onUploadChangeAvatar(response, file, fileList) {
                // console.log(response)
                //上传头像成功，返回Url
                if (this.modal_add)
                    this.formAdd.avatarUrl = response.msg
                else
                    this.formChange.avatarUrl = response.msg
            },
            querySearch() {
                this.loading = true
                let dates = this.search.dates
                if (dates.length < 2){
                    this.search.dates = ['','']
                }
                if (dates.length === 2) {
                    this.search.dates = [dateToString(dates[0]), dateToString(dates[1])]
                }
                this.search.page = this.current
                this.search.size = this.pageSize

                this.request({
                    url: '/user/search',
                    method: 'get',
                    params: this.search,
                    paramsSerializer: params => {
                        return this.$qs.stringify(params, {indices: false})
                    }
                }).then(res => {
                    this.data = res.data.content
                    this.pageData = res.data
                    // console.log(this.data)
                }).finally(() => {
                    this.loading = false
                })
            },
            searchSubmit() {
                //条件搜索
                this.current = 1
                this.isSearch = true
                this.querySearch();
            },
            showResetModal(row) {
                if (!this.$store.state.isAdmin){
                    this.$Message.error('你没有此操作权限!');
                    return;
                }
                //重置密码
                this.reset.password = ''
                this.reset.row = row
                this.modal_reset = true
                //输入框自动聚焦
                this.$nextTick(() => {
                    this.$refs.inputResetPassword.$refs.input.focus()
                })
            },
            resetPassword(name) {
                //重置密码
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.loading = true
                        this.request({
                            url: '/user/password',
                            method: 'put',
                            params: {id: this.reset.row.userId, password: this.reset.password}
                        }).then(res => {
                            this.$Message.success(res.msg);
                        }).finally(()=>{
                            this.loading = false
                        })
                    } else {
                        this.$Message.error('填写内容不符合要求!');
                    }
                })
            },
            deleteList() {
                this.$Modal.confirm({
                    title: '提醒',
                    content: '确定要删除所选中的所有管理员数据？',
                    onOk: () => {
                        this.loading = true
                        this.request({
                            url: '/user/list',
                            method: 'delete',
                            params: {ids: this.selectIds},
                            paramsSerializer: params => {
                                return this.$qs.stringify(params, {indices: false})
                            }
                        }).then(res => {
                            this.$Message.info(res.msg);
                            this.refreshData(); //更新当前页面
                        }).finally(() => {
                            this.loading = false
                        })
                    },
                    onCancel: () => {
                        this.$Message.info('已取消删除');
                    }
                });
            },
            getArea (value, selectedData) {
                const areaName = selectedData.map(item => item.label)
                let chinaArea = [...areaName]
                this.chinaArea = chinaArea
                if (chinaArea.length === 3) {
                    /*this.address.areaInfo.province = chinaArea[0]
                    this.address.areaInfo.city = chinaArea[1]
                    this.address.areaInfo.district = chinaArea[2]*/
                    let address = chinaArea[0] + chinaArea[1] + chinaArea[2]
                    if (this.modal_add){
                        this.formAdd.address = address
                    }else {
                        this.formChange.address = address
                    }
                }
            },
            getStatus(status) {
                return status === 1
            },
            changeStatus(row){
                if (!this.$store.state.isAdmin){
                    this.$Message.error('你没有此操作权限!');
                    return;
                }

                let that = this
                let str = row.status === 1 ? '禁用' : '正常'
                this.$Modal.confirm({
                    title: '提醒',
                    content: '确定要将' + row.name + '的账号状态改为' + str + '状态？',
                    onOk: () => {
                        let data = {}
                        data.userId = row.userId
                        data.status = row.status === 1 ? 0 : 1
                        this.loading = true
                        this.request({
                            url: '/user',
                            method: 'put',
                            data: JSON.stringify(data),
                        }).then(res => {
                            this.refreshData();        //更新修改行的数据
                            if(data.status === 0){
                                //强制下线 住户
                                that.request({
                                    url: '/delete/user/' + row.userId,
                                    method: 'delete'
                                }).then(response => {
                                    that.$Message.success(res.msg);
                                })
                            }else {
                                this.$Message.success(res.msg);
                            }
                        }).finally(() => {
                            this.loading = false
                        })
                    },
                    onCancel: () => {
                        this.$Message.info('已取消');
                    }
                });
            },
            exportExcel(){
                exportExcel('/user/export/excel',this.selectIds)
            }
        }
    }
</script>

<style scoped>

</style>
